<?php
/*
 * @Descripttion: 关键词模型
 * @Author: 夜雨
 * @Email: 448408740@qq.com
 * @Date: 2019-11-27 09:58:10
 * @LastEditTime: 2019-12-04 15:44:48
 */
namespace app\admin\model;

use think\Db;
use think\Model;
use think\facade\Log;

class Keyword extends Model
{
    protected $table = 'bsa_keyword';

    /**
     * @msg: 获取关键词
     * @param int $limit
     * @param string $where
     * @return: json
     */
    public function getKeyword($limit, $where)
    {
        $prefix = config('database.prefix');

        try {

            $res = $this->field($prefix . 'keyword.*')->where($where)
                ->order('total', 'desc')->paginate($limit);

        }catch (\Exception $e) {
            Log::error($e->getMessage());
            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, $res, 'ok');
    }

    /**
     * @msg: 根据ID 获取信息
     * @param int $id 
     * @return: json
     */
    public function getKeywordById($id)
    {
        try {

            $res = $this->where('kid', $id)->find();

        }catch (\Exception $e) {
            Log::error($e->getMessage());
            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, $res, '获取成功');
    }

    /**
     * @msg: 添加
     * @param array $param
     * @return array
     */
    public function addKeyword($param)
    {
        try {
            $getid = 0;
            $res = $this->where('keyword', $param['keyword'])->find();
            if(empty($res)){
                $getid = $this->insertGetId(['keyword' => $param['keyword']]);
            }else{
                $this->where('kid', $res['kid'])->setInc('total', 1);
                $getid = $res['kid'];
            }
            $filed = $param['ism'] == 1 ? 'totalpc' : 'totalm';
            $this->where('kid', $getid)->setInc($filed, 1);
        }catch (\Exception $e) {
            Log::error($e->getMessage());
            return modelReMsg(-1, 0, $e->getMessage());
        }
        return modelReMsg(0, $getid, '添加成功');
    }

    /**
     * @msg: 删除
     * @param int $id
     * @return array
     */
    public function delKeywordById($id)
    {
        try {
            $this->where('kid', $id)->delete();
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return modelReMsg(-1, '', $e->getMessage());
        }
        return modelReMsg(0, '', '删除成功');
    }
    
}